package com.ruoyi.web.controller.file;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.Enums;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.file.domain.FileRecode;
import com.ruoyi.file.service.IFileRecodeService;
import com.ruoyi.file.utils.FileEnAES;
import com.ruoyi.file.utils.FileEnBase64;
import com.ruoyi.file.utils.FileEnPBE;
import com.ruoyi.web.controller.common.CommonController;
import org.hibernate.sql.Update;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import static com.ruoyi.common.utils.file.FileUploadUtils.getDefaultBaseDir;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2023-03-13
 */
@RestController
@RequestMapping("/file/recode")
public class FileRecodeController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(FileRecodeController.class);
    @Autowired
    private IFileRecodeService fileRecodeService;
    private static final String KEYPATH = "Key1.dat";
    private static final String KEY = "BISHE";

    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('file:recode:list')")
    @GetMapping("/list")
    public TableDataInfo list(FileRecode fileRecode)
    {
        startPage();
        Long userId = getUserId();
        if (userId != null && userId != 1) {
            fileRecode.setCreateUserId(userId);
            fileRecode.setCreateUserName(getUsername());
        }
        List<FileRecode> list = fileRecodeService.selectFileRecodeList(fileRecode);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('file:recode:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FileRecode fileRecode)
    {
        List<FileRecode> list = fileRecodeService.selectFileRecodeList(fileRecode);
        ExcelUtil<FileRecode> util = new ExcelUtil<FileRecode>(FileRecode.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('file:recode:query')")
    @GetMapping(value = "/{fileId}")
    public AjaxResult getInfo(@PathVariable("fileId") Long fileId)
    {
        return success(fileRecodeService.selectFileRecodeByFileId(fileId));
    }

    /**
     * 新增【请填写功能名称】
     */
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody List<FileRecode> list){
        fileRecodeService.insertFileRecode(list, getLoginUser().getUser());
        return toAjax(1);
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('file:recode:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FileRecode fileRecode) {
        String path = RuoYiConfig.getProfile() + StringUtils.substringAfter(fileRecode.getUrl(), Constants.RESOURCE_PREFIX);
        if (Enums.EncryptStatus.YES.getValue().equals(fileRecode.getIsEncrypt())) {
            // 加密文件
            fileRecodeService.encryption(fileRecode,path);
        }else {
            // 解密文件
            fileRecodeService.decryption(fileRecode,path);
        }
        return toAjax(fileRecodeService.updateFileRecode(fileRecode));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('file:recode:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{fileIds}")
    public AjaxResult remove(@PathVariable Long[] fileIds)
    {
        return toAjax(fileRecodeService.deleteFileRecodeByFileIds(fileIds));
    }

    /**
     * 加密文件下载
     */
    @PostMapping("/en/download")
    public void enDownload(FileRecode fileRecode, HttpServletRequest request, HttpServletResponse response)
            throws Exception{
        String path = RuoYiConfig.getProfile() + StringUtils.substringAfter(fileRecode.getUrl(), Constants.RESOURCE_PREFIX);
        fileRecodeService.decryption(fileRecode, path);
        try
        {
            // 本地资源路径
            // 数据库资源地址
            String downloadPath = RuoYiConfig.getProfile() + StringUtils.substringAfter(fileRecode.getUrl(), Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }finally {
            // 再次加密
            fileRecodeService.encryption(fileRecode, path);
        }
    }

    /**
     * 普通文件下载
     */
    @PostMapping("/de/download")
    public void deDownload(FileRecode fileRecode, HttpServletRequest request, HttpServletResponse response)
            throws Exception{
        try
        {
            // 本地资源路径
            // 数据库资源地址
            String downloadPath = RuoYiConfig.getProfile() + StringUtils.substringAfter(fileRecode.getUrl(), Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
}
